package com.wanghua.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.dto.mq.OrderDto;
import com.wanghua.common.dto.mq.SecKillOrderDto;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;
import com.wanghua.common.utils.R;
import com.wanghua.common.vo.UserResponseVo;
import com.wanghua.mall.order.config.OrderRabbitMQConfig;
import com.wanghua.mall.order.constant.OrderConstant;
import com.wanghua.mall.order.dao.OrderDao;
import com.wanghua.mall.order.entity.OrderEntity;
import com.wanghua.mall.order.entity.OrderItemEntity;
import com.wanghua.mall.order.entity.PaymentInfoEntity;
import com.wanghua.mall.order.enums.OrderStatusEnum;
import com.wanghua.mall.order.interceptor.OrderInterceptor;
import com.wanghua.mall.order.openfeign.CartClient;
import com.wanghua.mall.order.openfeign.ProductClient;
import com.wanghua.mall.order.openfeign.UserClient;
import com.wanghua.mall.order.openfeign.WareClient;
import com.wanghua.mall.order.service.OrderItemService;
import com.wanghua.mall.order.service.OrderService;
import com.wanghua.mall.order.service.PaymentInfoService;
import com.wanghua.mall.order.to.OrderCreateTo;
import com.wanghua.mall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private UserClient userClient;
    @Resource
    private CartClient cartClient;
    @Resource
    private WareClient wareClient;
    @Resource
    private ProductClient productClient;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 为订单结算页面准备数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        UserResponseVo userResponseVo = OrderInterceptor.threadLocal.get();
        //每个线程共享请求数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1.远程查询用户的收货地址
        CompletableFuture<Void> getAddressCompletableFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);//解决异步调用request不共享问题
            List<UserReceiveAddressVo> userReceiveAddressVoList = userClient.getAddressByUserId(userResponseVo.getId());
            orderConfirmVo.setUserReceiveAddressVoList(userReceiveAddressVoList);
        }, threadPoolExecutor);
        //2.远程查询购物车中所有被选中的购物项
        CompletableFuture<Void> getOrderItemCompletableFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);//解决异步调用request不共享问题
            List<OrderItemVo> orderItemVoList = cartClient.getCheckedItemsByUser();
            orderConfirmVo.setOrderItemVoList(orderItemVoList);
        }, threadPoolExecutor).thenRunAsync(() -> {
            List<OrderItemVo> orderItemVoList = orderConfirmVo.getOrderItemVoList();
            List<Long> skuIdList = orderItemVoList.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareClient.getStockBySku(skuIdList);
            Map<Long, Boolean> map = (Map<Long, Boolean>) r.get("data");
            confirmOrder().setStock(map);
        }, threadPoolExecutor);
        //3.查询用户积分
        Integer integration = userResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //4.防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        orderConfirmVo.setOrderToken(token);
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX + userResponseVo.getId().toString(),
                token, 30, TimeUnit.MINUTES);

        try {
            CompletableFuture.allOf(getAddressCompletableFuture, getOrderItemCompletableFuture).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderConfirmVo;
    }

    /**
     * 下单
     *
     * @param orderSubmitVo
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        OrderSubmitResponseVo orderSubmitResponseVo = new OrderSubmitResponseVo();
        //创建订单，校验令牌，校验价格，锁定库存

        //1.校验令牌[原子性]
        //lua脚本返回 0-临牌失败  1-校验成功
        UserResponseVo userResponseVo = OrderInterceptor.threadLocal.get();
        String submitOrderToken = orderSubmitVo.getOrderToken();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Collections.singletonList(OrderConstant.ORDER_TOKEN_PREFIX + userResponseVo.getId().toString()),
                submitOrderToken);
        if (result == 0L) {//校验令牌不通过
            orderSubmitResponseVo.setCode(1);
            return orderSubmitResponseVo;
        }
        //2.创建订单
        OrderCreateTo orderCreateTo = createOrder(orderSubmitVo);
        //3.校验价格
        BigDecimal payAmount = orderCreateTo.getOrderEntity().getPayAmount();
        BigDecimal payPrice = orderSubmitVo.getPayPrice();
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) > 0.01) {//价格校验不通过
            orderSubmitResponseVo.setCode(2);
            return orderSubmitResponseVo;
        }
        //4.保存订单到数据库
        saveOrder(orderCreateTo);
        //5.库存锁定
        WareSkuStockVo wareSkuStockVo = new WareSkuStockVo();
        wareSkuStockVo.setOrderNo(orderCreateTo.getOrderEntity().getOrderNo());
        wareSkuStockVo.setOrderItemVoList(orderCreateTo.getOrderItemEntityList().stream().map((orderItemEntity) -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(orderItemEntity.getSkuId());
            orderItemVo.setCount(orderItemEntity.getSkuQuantity());
            return orderItemVo;
        }).collect(Collectors.toList()));
        R r = wareClient.orderLockStock(wareSkuStockVo);
        if (r.getCode() != 0) {//锁定库存失败
            orderSubmitResponseVo.setCode(3);
            return orderSubmitResponseVo;
        }

        orderSubmitResponseVo.setCode(0);
        orderSubmitResponseVo.setOrderEntity(orderCreateTo.getOrderEntity());
        //订单创建成功，发送消息给RabbitMQ
        rabbitTemplate.convertAndSend(OrderRabbitMQConfig.ORDER_EVENT_EXCHANGE_NAME,
                OrderRabbitMQConfig.ORDER_CREATE_ORDER_BINDING_NAME,
                orderCreateTo.getOrderEntity());
        return orderSubmitResponseVo;
    }

    /**
     * 根据订单号获取订单状态
     *
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Integer getOrderStatus(String orderNo) {
        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_no", orderNo).select("status"));
        return orderEntity.getStatus();
    }

    /**
     * 关闭订单
     *
     * @param orderEntity
     */
    @Transactional
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询订单状态
        OrderEntity byId = baseMapper.selectById(orderEntity.getId());
        if (byId.getStatus().equals(OrderStatusEnum.PAYING.getCode())) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(byId.getId());
            update.setStatus(OrderStatusEnum.CANCELED.getCode());
            baseMapper.updateById(update);
            //发送
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orderEntity, orderDto);
            try {

                rabbitTemplate.convertAndSend(OrderRabbitMQConfig.ORDER_EVENT_EXCHANGE_NAME,
                        "order.release.other.#", orderDto);
            } catch (Exception e) {
                //TODO 未发送成功的消息要重复发送
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建订单需要支付的数据
     *
     * @param orderNo 订单号
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderNo) {
        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_no", orderNo));
        PayVo payVo = new PayVo();
        payVo.setOrderNo(orderNo);
        payVo.setTradeNo(orderNo);
        payVo.setTotalAmount(orderEntity.getTotalAmount().setScale(2, RoundingMode.CEILING).toString());
        payVo.setSubject("华为荣耀9x");
        payVo.setReturnUrl("http://user.mall.com/userOrder.html");
        return payVo;
    }

    /**
     * 查询某个用户的订单列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        UserResponseVo userResponseVo = OrderInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("user_id", userResponseVo.getId()).orderByDesc("gmt_create")
        );
        List<OrderEntity> orderEntityList = page.getRecords().stream().map((orderEntity) -> {
            List<OrderItemEntity> orderItemEntityList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_no", orderEntity.getOrderNo()));
            orderEntity.setOrderItemEntityList(orderItemEntityList);
            return orderEntity;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }


    /**
     * 处理支付宝支付的返回结果
     *
     * @param payAsyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        //保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setOrderNo(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setSubject(payAsyncVo.getSubject());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setTotalAmount(new BigDecimal(payAsyncVo.getTotal_amount()));
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        //修改订单状态
        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功
            String orderNo = payAsyncVo.getOut_trade_no();
            baseMapper.updateOrderStatus(orderNo, OrderStatusEnum.PAYED.getCode());
            return "success";
        }
        return "fail";
    }


    /**
     * 创建秒杀订单
     * @param secKillOrderDto
     */
    @Override
    public void createSecKillOrder(SecKillOrderDto secKillOrderDto) {
        //TODO 创建秒杀订单

    }


    /**
     * 保存订单到数据库
     *
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity orderEntity = orderCreateTo.getOrderEntity();
        List<OrderItemEntity> orderItemEntityList = orderCreateTo.getOrderItemEntityList();

        baseMapper.insert(orderEntity);
        orderItemService.saveBatch(orderItemEntityList, orderItemEntityList.size());
    }

    /**
     * 创建订单
     *
     * @param orderSubmitVo
     * @return
     */
    private OrderCreateTo createOrder(OrderSubmitVo orderSubmitVo) {
        //1.生成订单号
        String orderNo = IdWorker.getTimeId();
        //2.创建数据库中订单
        OrderEntity orderEntity = buildOrderEntity(orderSubmitVo, orderNo);
        //3.创建数据库中订单商品项
        List<OrderItemEntity> orderItemEntityList = buildOrderItemEntityList(orderNo);
        //4.校验价格
        computePrice(orderEntity, orderItemEntityList);


        OrderCreateTo orderCreateTo = new OrderCreateTo();
        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setOrderItemEntityList(orderItemEntityList);
        return orderCreateTo;
    }

    /**
     * 校验价格/积分与成长值
     *
     * @param orderEntity         orderEntity
     * @param orderItemEntityList orderItemEntityList
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntityList) {
        //订单总额
        BigDecimal totalAmount = new BigDecimal(0);
        //促销优化金额（促销价、满减、阶梯价）
        BigDecimal promotionAmount = new BigDecimal(0);
        //积分抵扣金额
        BigDecimal integrationAmount = new BigDecimal(0);
        //优惠券抵扣金额
        BigDecimal couponAmount = new BigDecimal(0);
        //后台调整订单使用的折扣金额
        BigDecimal discountAmount = new BigDecimal(0);
        //积分
        int integration = 0;
        //成长值
        int growth = 0;

        if (orderItemEntityList != null && orderItemEntityList.size() > 0) {
            for (OrderItemEntity orderItemEntity : orderItemEntityList) {
                totalAmount = totalAmount.add(orderItemEntity.getRealAmount());
                promotionAmount = promotionAmount.add(orderItemEntity.getPromotionAmount());
                integrationAmount = integrationAmount.add(orderItemEntity.getIntegrationAmount());
                couponAmount = couponAmount.add(orderItemEntity.getCouponAmount());
                integration += orderItemEntity.getGiftIntegration();
                growth += orderItemEntity.getGiftGrowth();
            }
        }
        //设置价格相关
        orderEntity.setTotalAmount(totalAmount);
        orderEntity.setPayAmount(totalAmount.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setDiscountAmount(discountAmount);
        //设置积分与成长值
        orderEntity.setIntegration(integration);
        orderEntity.setGrowth(growth);

    }


    /**
     * 创建数据库中订单
     *
     * @param orderSubmitVo
     * @return
     */
    private OrderEntity buildOrderEntity(OrderSubmitVo orderSubmitVo, String orderNo) {
        UserResponseVo userResponseVo = OrderInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();

        //1.订单号
        orderEntity.setOrderNo(orderNo);

        //2.用户信息
        //2.1用户id
        orderEntity.setUserId(userResponseVo.getId());
        //2.2用户姓名
        orderEntity.setUserName(userResponseVo.getUsername());
        //2.2用户下单时使用的积分
        orderEntity.setUseIntegration(userResponseVo.getIntegration());

        //3.收货地址
        R r = wareClient.getFare(orderSubmitVo.getAddressId());
        FareVo fareVo = (FareVo) r.get("data");
        //3.1运费
        orderEntity.setFreightAmount(fareVo.getFare());
        UserReceiveAddressVo userReceiveAddressVo = fareVo.getAddress();
        //3.2收货城市
        orderEntity.setReceiverCity(userReceiveAddressVo.getCity());
        //3.3收货省份（直辖市）
        orderEntity.setReceiverProvince(userReceiveAddressVo.getProvince());
        //3.4收货地区
        orderEntity.setReceiverRegion(userReceiveAddressVo.getRegion());
        //3.5详细地址
        orderEntity.setReceiverDetailAddress(userReceiveAddressVo.getDetailAddress());

        //4.收货人信息
        //4.1收货人姓名
        orderEntity.setReceiverName(userReceiveAddressVo.getName());
        //4.2收货人电话
        orderEntity.setReceiverPhone(userReceiveAddressVo.getPhone());
        //4.3收货人邮编
        orderEntity.setReceiverPostCode(userReceiveAddressVo.getPostCode());

        //5.订单备注
        orderEntity.setNote(orderSubmitVo.getNote());

        //6.支付方式
        orderEntity.setPayType(orderSubmitVo.getPayType());

        //7.订单状态
        orderEntity.setStatus(OrderStatusEnum.PAYING.getCode());

        //8.自动确认时间（天）
        orderEntity.setAutoConfirmDay(7);

        //9.删除状态【0->未删除；1->已删除】
        orderEntity.setDeleteStatus(0);

        return orderEntity;
    }

    /**
     * 创建数据库中订单商品项的集合
     *
     * @param orderNo
     * @return
     */
    private List<OrderItemEntity> buildOrderItemEntityList(String orderNo) {
        List<OrderItemVo> orderItemVoList = cartClient.getCheckedItemsByUser();
        if (orderItemVoList != null && orderItemVoList.size() > 0) {
            return orderItemVoList.stream().map((orderItemVo -> buildOrderItemEntity(orderItemVo, orderNo))).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 创建数据库中订单商品项的单个
     *
     * @param orderItemVo
     * @param orderNo     订单号
     * @return
     */
    private OrderItemEntity buildOrderItemEntity(OrderItemVo orderItemVo, String orderNo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.订单信息
        orderItemEntity.setOrderNo(orderNo);
        //2.spu信息
        Long skuId = orderItemVo.getSkuId();
        R r = productClient.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = (SpuInfoVo) r.get("data");
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());// TODO spu品牌名待完善
        orderItemEntity.setCategoryId(spuInfoVo.getCategoryId());
        orderItemEntity.setSpuImage(spuInfoVo.getSpuDescription());// TODO spu图片待完善
        //3.sku信息
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuImage(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        orderItemEntity.setSkuAttrsValues(StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";"));
        //4.优惠信息
        orderItemEntity.setPromotionAmount(new BigDecimal(0));
        orderItemEntity.setCouponAmount(new BigDecimal(0));
        orderItemEntity.setIntegrationAmount(new BigDecimal(0));
        BigDecimal originalPrice = orderItemEntity.getSkuPrice()
                .multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal realAmount = originalPrice
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realAmount);
        //5.积分信息 待完善 TODO
        orderItemEntity.setGiftGrowth(orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity())).intValue());
        orderItemEntity.setGiftIntegration(orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity())).intValue());


        return orderItemEntity;

    }

}